package cn.duapi.weblauncher;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppClassLoader;
import org.eclipse.jetty.webapp.WebAppContext;

public class JettyServer {

	public static final int PORT = 8080;

	/**
     * 创建用于开发运行调试的Jetty Server, 默认以src/main/webapp为Web应用目录, 可以配置webContext变更
     */
    public static Server createServerInSource(int port, WebAppContext webContext) {

		Server server = new Server(port);
		// 设置在JVM退出时关闭Jetty的钩子。
		server.setStopAtShutdown(true);

		server.setHandler(webContext);

		return server;
	}

    /**
     * 
     * @param port
     * @param webApp
     *            src/main/webapp
     * @param webXml
     *            src/main/webapp/WEB-INF/web.xml
     * @param contextPath
     *            /
     */
    public static void start(int port, String webApp, String webXml, String contextPath) {

        AppContextBuilder builder = new AppContextBuilder();

        WebAppContext context = builder.buildWebAppContent();

        context.setContextPath(contextPath);

        context.setResourceBase(webApp);

        context.setDefaultsDescriptor(webXml);//`deafults` can find the xml in classpath*, but setDescriptor can not

        final Server server = JettyServer.createServerInSource(port, context);

        JettyServer.start(server);
    }

	public static void reloadContext(Server server) throws Exception {
		WebAppContext context = (WebAppContext) server.getHandler();

		System.out.println("[INFO] Application reloading");
		context.stop();

		WebAppClassLoader classLoader = new WebAppClassLoader(context);
		classLoader.addClassPath("target/classes");
		classLoader.addClassPath("target/test-classes");
		context.setClassLoader(classLoader);

		context.start();

		System.out.println("[INFO] Application reloaded");
	}

	public Server createServer(int port) {
		return createServerInSource(port, new AppContextBuilder().buildWebAppContent());
	}

	public Server createServer(int port, String contextPath) {
		return createServerInSource(port, new AppContextBuilder().buildWebAppContent(contextPath));
	}

	/**
	 * Run a jetty server for test
	 * 
	 * @param port
	 * @param contextPath
	 */
	public static void startJetty(int port, String contextPath) {
		start(initServer(port, contextPath));
	}

	static Server initServer(int port, String contextPath) {
		System.setProperty("spring.profiles.active", "development");
		Server server;
		if (contextPath == null) {
			server = new JettyServer().createServer(port);
		} else {
			server = new JettyServer().createServer(port, contextPath);
		}
		return server;
	}

    public static void start(Server server) {
		try {
			server.stop();
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public static void startJetty(int port) {
		start(initServer(port, null));
	}

	public static void main(String[] args) {
		startJetty(8080, "");
	}

}
